#include <QgsSimulation/DistanceMeasurementTool.h>

using SimulationCore::QgsSimulation::DistanceMeasurementTool;

DistanceMeasurementTool::DistanceMeasurementTool(QgsMapCanvas* mapcanvas, const QString& action)
	: QgsMapToolEmitPoint(mapcanvas),
	mapcanvas_(mapcanvas), action_(action)
{
    this->crs_ = this->mapcanvas_->mapSettings().destinationCrs();

	this->line_rubber_band_ = new QgsRubberBand(this->mapcanvas_, QgsWkbTypes::LineGeometry);
	this->line_rubber_band_->setColor(Qt::blue);
	this->line_rubber_band_->setWidth(2);
	
}

DistanceMeasurementTool::~DistanceMeasurementTool()
{
    this->mapcanvas_->scene()->removeItem(this->line_rubber_band_);

	delete this->line_rubber_band_;

	this->line_rubber_band_ = nullptr;
}


void DistanceMeasurementTool::canvasPressEvent(QgsMapMouseEvent * e)
{
	if (e->button() == Qt::LeftButton) {
		this->points_.append(e->mapPoint());
		if(this->points_.size() > 1)
		{
			QgsGeometry geom = QgsGeometry::fromPolylineXY(this->points_);
			this->line_rubber_band_->setToGeometry(geom, this->crs_);
			emit drawGeometry(this->action_, QgsWkbTypes::LineString, geom, false);
		}
	}
	else if (e->button() == Qt::RightButton) {
		if (this->points_.size() > 1) {
			QgsGeometry geom = QgsGeometry::fromPolylineXY(this->points_);
			emit drawGeometry(this->action_, QgsWkbTypes::LineString, geom, true);
		}
		ClearGeometry();
	}
}

void DistanceMeasurementTool::canvasDoubleClickEvent(QgsMapMouseEvent * e)
{
	if (e->button() == Qt::LeftButton && this->points_.size() > 1) {
		QgsGeometry geom = QgsGeometry::fromPolylineXY(this->points_);
		emit drawGeometry(this->action_, QgsWkbTypes::LineString, geom, true);
		
		ClearGeometry();
	}
}

void DistanceMeasurementTool::activate()
{
	QgsMapToolEmitPoint::activate();
	mapcanvas_->setMouseTracking(true);
}

void DistanceMeasurementTool::deactivate()
{
	ClearGeometry();
	mapcanvas_->setMouseTracking(false);
	QgsMapToolEmitPoint::deactivate();
}

void SimulationCore::QgsSimulation::DistanceMeasurementTool::ClearGeometry()
{
	/*Çå³ý»º´æÊý¾Ý*/
	this->points_.clear();
	this->line_rubber_band_->reset(QgsWkbTypes::LineGeometry);
}
